import urllib
from HTMLParser import HTMLParser

import FilenameParser
from Episode import EpisodeInfo

target_url = "http://thepiratebay.org/top/205"

class TorrentInfo(EpisodeInfo):
  url     = None
  size    = None
  seeds   = None
  leeches = None

  def __repr__(self):
    return "%s  (%.1fMB s:%d l:%d)" % ( EpisodeInfo.__repr__(self)
                                      , self.size / (1024 * 1024)
                                      , self.seeds
                                      , self.leeches
                                      )



class TPBParser(HTMLParser):

  def __init__(self):
    HTMLParser.__init__(self)

  def reset(self):
    HTMLParser.reset(self)
    self.intd = False
    self.found_torrent = False
    self.table_data_index = 0
    self.current_row = {}
    self.rows = []

  def _close_current_row(self):
    self.table_data_index = 0
    self.rows.append(self.current_row)
    self.current_row = {}

  def handle_starttag(self, tag, attrs):
    if tag == 'a':
      attr_dict = dict(attrs)
      if 'title' in attr_dict and attr_dict['title'] == "Download this torrent":
        self.found_torrent = True
        self.current_row['url'] = attr_dict['href']
    if tag == 'td':
      self.intd = True

  def handle_endtag(self, tag):
    if tag == 'td':
      self.intd = False

  def handle_data(self, data):
    if self.intd and self.found_torrent:
      if   self.table_data_index == 0:
        self.current_row['size'] = float(data)
      elif self.table_data_index == 1:
        if data == 'MiB':
            self.current_row['size'] *= 1024 * 1024
        if data == 'GiB':
            self.current_row['size'] *= 1024 * 1024 * 1024
      elif self.table_data_index == 2:
        self.current_row['seeds'] = int(data) 
      elif self.table_data_index == 3:
        self.current_row['leeches'] = int(data) 
      else:
        self.found_torrent = False
        self._close_current_row()
        return
      self.table_data_index += 1

def get_tpb_data(page = None):
  if not page:
    page = urllib.urlopen(target_url)

  page_parser = TPBParser()
  name_parser = FilenameParser.parser1()

  page_parser.feed(page.read())

  torrent_infos = []
  for row in page_parser.rows:
    episode_info = name_parser(row['url'])
    if episode_info:
      torrent_info = TorrentInfo( episode_info.series_name
                                , episode_info.series_number
                                , episode_info.episode_number
                                )
      torrent_info.__dict__.update(row)
      torrent_infos.append(torrent_info)
  return torrent_infos


    

if __name__ == "__main__":
  page = open('tpb.html')
  data = get_tpb_data(page)
  print data
